package arina.sh.ethernetcontrol;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;



public class SendEthernetControl
{
	
	public String getSTR_SERVER_ADDRESS() {
		return STR_SERVER_ADDRESS;
	}
	public void setSTR_SERVER_ADDRESS(String sTR_SERVER_ADDRESS) {
		STR_SERVER_ADDRESS = sTR_SERVER_ADDRESS;
	}
	
	public int getUDP_SERVER_PORT() {
		return UDP_SERVER_PORT;
	}
	public void setUDP_SERVER_PORT(int uDP_SERVER_PORT) {
		UDP_SERVER_PORT = uDP_SERVER_PORT;
	}

	private int UDP_SERVER_PORT ;
	private String STR_SERVER_ADDRESS ;
	public SendEthernetControl(int m_udp_server_port,String m_server_address)
	{
		UDP_SERVER_PORT=m_udp_server_port;
		STR_SERVER_ADDRESS=m_server_address;
	}
	
	public void sendCommand(COMMAND_TYPE cmd_type,int subnet_id,int device_id,int device_channel,int brightness_level)
	{
		byte[]udpMsg= makeDataToSend(cmd_type,subnet_id,device_id,device_channel,brightness_level);
		DatagramSocket ds=null;
		try{
		ds= new DatagramSocket();
		
		InetAddress serverAddress= InetAddress.getByName(STR_SERVER_ADDRESS);
		DatagramPacket dp=new DatagramPacket(udpMsg,udpMsg.length,serverAddress,UDP_SERVER_PORT);
		ds.send(dp);
		}
		catch(SocketException e)
		{
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(ds!=null)
				ds.close();
		}
		
	}
	private byte[] makeDataToSend(COMMAND_TYPE cmd_type,int SUBNET_ID,int DEVICE_ID,int DEVICE_CHANNEL ,int BRIGHTNESS_VARIABLE ) {
		// TODO Auto-generated method stub
		byte code;
		switch (cmd_type) {
		case ON_OFF:
			code=0x31;
			break;
		case REVERSE:
			code=0x1c;
			break;
		case READ_STATUS:
			code=0x33;
			break;

		default:
			code=0x33;
			break;
		}
		byte[] udpMsg = new byte[]
				{
	        (byte) 83,
	        (byte) 77,
	        (byte) 65,
	        (byte) 82,
	        (byte) 84,
	        (byte) 72,
	        (byte) 79,
	        (byte) 85,
	        (byte) 83,
	        (byte) 69,
	        (byte) 0x73,
	        (byte)0x6D,
	        (byte)0x61,
	        (byte)0x72,
	        (byte)0x74,
	        (byte)0x74,
	        (byte)0x6E,
	        (byte)0x68,
	        (byte)0x31,
	        (byte)0x32,
	        (byte)0x33,
	        (byte)0x34,
	        (byte)0x35,
	        (byte)0x36,
	        (byte)0x00,
	        code,
	        (byte)SUBNET_ID,
	        (byte)DEVICE_ID,
	        (byte)DEVICE_CHANNEL,
	        (byte)BRIGHTNESS_VARIABLE,
	        (byte)0x00,
	        (byte)0x00
	      };
		return udpMsg;
	}
	
}

